package com.syxbyi.yudong.class01;

public class MyCircularDeque {

    private final int[] arr;
    private int size;
    private int head;               // 除非队列满，否则 arr[head], arr[tail] 都没有元素
    private int tail;

    public MyCircularDeque(int k) {
        arr = new int[k];
        size = 0;
        head = 0;
        tail = 1;
    }

    private int getIndex(int index) {
        if (index >= 0) {
            return index % arr.length;
        }
        while (index < 0) {
            index += arr.length;
        }
        return index;
    }

    /** Adds an item at the front of Deque. Return true if the operation is successful. */
    public boolean insertFront(int value) {
        if (isFull()) {
            return false;
        }
        arr[head--] = value;
        head = getIndex(head);          // 因此此时 head 可能减到 -1
        size++;
        return true;
    }

    /** Adds an item at the rear of Deque. Return true if the operation is successful. */
    public boolean insertLast(int value) {
        if (isFull()) {
            return false;
        }
        arr[tail++] = value;
        tail = getIndex(tail);          // 此时 tail 可能越界
        size++;
        return true;
    }

    /** Deletes an item from the front of Deque. Return true if the operation is successful. */
    public boolean deleteFront() {
        if (isEmpty()) {
            return false;
        }
        head = getIndex(++head);        // 不需要真的删除 arr[head]
        size--;
        return true;
    }

    /** Deletes an item from the rear of Deque. Return true if the operation is successful. */
    public boolean deleteLast() {
        if (isEmpty()) {
            return false;
        }
        tail = getIndex(--tail);
        size--;
        return true;
    }

    /** Get the front item from the deque. */
    public int getFront() {
        if (isEmpty()) {
            return -1;
        }
        return arr[getIndex(head + 1)];
    }

    /** Get the last item from the deque. */
    public int getRear() {
        if (isEmpty()) {
            return -1;
        }
        return arr[getIndex(tail - 1)];
    }

    /** Checks whether the circular deque is empty or not. */
    public boolean isEmpty() {
        return size == 0;
    }

    /** Checks whether the circular deque is full or not. */
    public boolean isFull() {
        return size == arr.length;
    }

}
